package com.captjack.websocket.websocket.base;

import com.captjack.common.util.thread.ThreadPoolFactory;
import org.apache.commons.lang3.StringUtils;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicLong;

/**
 * socket统一管理
 *
 * @author Capt Jack
 * @date 2018/7/24
 */
public enum AllWebSocketManager {

    /**
     *
     */
    INSTANCE;

    /**
     * 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    public static final AtomicLong ON_LINE_COUNT = new AtomicLong(0L);

    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
     */
    private static final Map<String, Session> HELLO_WEB_SOCKETS = new ConcurrentHashMap<>();

    /**
     * 群发消息线程池
     */
    private static final ExecutorService CACHE_THREAD_POOL = ThreadPoolFactory.newCachedThreadPool("web-socket-manager-");

    /**
     * 添加客户端到session
     *
     * @param id      id
     * @param session 会话
     */
    public void addSocketClient(String id, Session session) {
        HELLO_WEB_SOCKETS.put(id, session);
    }

    /**
     * 删除下线客户端
     *
     * @param id id
     */
    public void deleteSocketClient(String id) {
        HELLO_WEB_SOCKETS.remove(id);
    }

    /**
     * 群发消息（所有在线的客户端）
     *
     * @param message 消息
     * @throws IOException 异常
     */
    public void sendMessageToAll(String message) throws IOException {
        CACHE_THREAD_POOL.execute(() -> {
            for (Map.Entry<String, Session> entry : HELLO_WEB_SOCKETS.entrySet()) {
                try {
                    sendMessageById(entry.getKey(), message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 单发消息
     *
     * @param id      标识
     * @param message 消息
     * @throws IOException 异常
     */
    public void sendMessageById(String id, String message) throws IOException {
        if (StringUtils.isNotBlank(message)) {
            HELLO_WEB_SOCKETS.get(id).getBasicRemote().sendText(message);
        }
    }

}
